package tp.pr3.instructions;

import tp.pr3.Message;
import tp.pr3.NavigationModule;
import tp.pr3.RobotEngine;
import tp.pr3.instructions.exceptions.InstructionExecutionException;
import tp.pr3.instructions.exceptions.WrongInstructionFormatException;
import tp.pr3.items.Item;
import tp.pr3.items.ItemContainer;

public class ScanInstruction implements Instruction {

	@Override
	public Instruction parse(String cad) throws WrongInstructionFormatException {
		String[] words = cad.split(" ");
		for (String i : Message.SCAN_INSTRUCTION) {
			if (words[0].equalsIgnoreCase(i))
				return new ScanInstruction();
		}
		throw new WrongInstructionFormatException(Message.NOT_UNDERSTAND);
	}

	@Override
	public String getHelp() {
		String help = Message.SCAN_INSTRUCTION[0];
		for (int i = 1; i < Message.SCAN_INSTRUCTION.length; i++)
			help += "|" + Message.SCAN_INSTRUCTION[i];
		help += " [id]";
		return help;
	}

	@Override
	public void configureContext(RobotEngine engine,
			NavigationModule navigation, ItemContainer robotContainer) {
		this.engine = engine;
		this.robotContainer = robotContainer;
	}

	@Override
	public void execute() throws InstructionExecutionException {
		if (this.robotContainer.numberOfItems() == 0)
			throw new InstructionExecutionException(Message.EMPTY_INVENTORY.toString());
		else if (id == null)
			System.out.println(Message.SHOWING_ITEMS.toString().replace("<ids>", this.robotContainer.toString()));
		else {
			Item it = this.robotContainer.getItem(id);
			if (it != null)
				System.out.println(it.toString());
			else{
				throw new InstructionExecutionException(Message.NO_ITEM.toString());
			}
		}
	}
	
	private RobotEngine engine;
	private ItemContainer robotContainer;
	private String id;

}
